<?php

// phpMyRealty 3
//
// File Name: editgallery.php
// File Location : ./admin
//
// Copyright (c)2009 phpMyRealty.com
//
// e-mail: support@phpMyRealty.com

// Include configuration file and general functions
define('PMR', 'true');
define('PMRADMIN', 'true');

include ( '.././config.php' );
include ( PATH . '/defaults.php' );

// ----------------------------------------------------------------------
// ADMIN SECTION / EDIT LISTING PHOTO GALLERY

// Title tag content
$title = $lang['Photo_Gallery'];

// Template header
include ( PATH . '/admin/template/header.php' );

// If logged we can start the page output
if (adminAuth($session->fetch('adminlogin'), $session->fetch('adminpassword')))

 {
  // Include navigation panel
  include ( PATH . '/admin/navigation.php' );

  // Make sure this administrator have access to this script
  adminPermissionsCheck('manage_gallery', $session->fetch('adminlogin')) or error ('Critical Error', 'Incorrect privileges');

  // Make sure the get variables passed to the script are okay
  if (isset($_GET['id']) && eregi('^[0-9]+$', $_GET['id'])
  && isset($_GET['userid']) && eregi('^[0-9]+$', $_GET['userid']))

   {

    // Fetching the listing data 
    $sql = 'SELECT * FROM ' . PROPERTIES_TABLE . ' WHERE id = "' . safehtml($_GET['id']) . '" LIMIT 1';
    $r = $db->query( $sql );
    $f = $db->fetcharray( $r );

    // If the Submit button was pressed we start this routine

    // If user submitted a new gallery information or updated an
    // old one we add it or update the old record in the database

    // If user submitted a new gallery information or updated an
    // old one we add it or update the old record in the database
    if (((isset($_POST['submit_gallery']) 
    && $_POST['submit_gallery'] == $lang['Photo_Gallery_Submit'])) 
    OR ((isset($_POST['update_gallery']) 
    && $_POST['update_gallery'] == $lang['Photo_Gallery_Update'])))
     {

      $form = array();
      $form = array_map('safehtml', $_POST);
      $form['description'] = substr ($form['description'], 0, $conf['gallery_description_size']);

      echo table_header ( $lang['Information'] );

      // Initially we think that no errors were found
      $count_error = 0;

      // Check for the empty or incorrect required fields

      // Check if this user have reached the maximum
      // number of possible photos set by admin
      $sql = 'SELECT * FROM ' . GALLERY_TABLE . ' WHERE listingid = ' . $f['id'];
      $r = $db->query($sql) or error ('Critical Error', mysql_error () );

      if ($db->numrows($r) >= $conf['max_number_of_photos'] )
       { echo $lang['Maximum_Number_Of_Photos_Reached'] . '<br />'; $count_error++;}

      if (empty($form['title']) || strlen($form['title']) < 4 )
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Photo_Gallery_Title'] . '</span><br />'; $count_error++;}

      if (empty($form['id']) && !isset($_POST['submit_gallery']))
       { echo $lang['Field_Empty'] . ' - <span class="warning">ID</span><br />'; $count_error++;}

      if (empty($_FILES['image_file']['tmp_name']))
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Image_File'] . '</span><br />'; $count_error++;}

      //

      if ($count_error > '0')
       echo '<br /><span class="warning">' . $lang['Errors_Found'] . ': ' . $count_error . '</span><br />';

      // If no errors were found during the above checks we continue
      if ($count_error == '0')
       {
        // Update user details in the database

        // Get the user IP address
        $user_ip = $_SERVER['REMOTE_ADDR'];
        // If there is more than one IP
        // get the first one from the 
        // comma separated list
        if ( strstr($user_ip, ', ') ) 
         {
          $ips = explode(', ', $user_ip);
          $user_ip = $ips[0];
         }

        // If the gallery details were submitted
        // we generate the INSERT query
        if (isset($_POST['submit_gallery']) 
        && $_POST['submit_gallery'] == $lang['Photo_Gallery_Submit'])

         // Create a mysql query
         $sql = 'INSERT INTO '. GALLERY_TABLE .
         ' (userid, listingid, title, description, date_added, ip_added) 
  	 VALUES
	 ("' . $_GET['userid'] . '", "' . $f['id'] . '", "' . $form['title'] . '",
	  "' . $form['description']. '", "' . date('Y-m-d') . '",
	  "' . $user_ip . '")';

        // If the gallery details were update we do UPDATE
        if (isset($_POST['update_gallery']) 
        && $_POST['update_gallery'] == $lang['Photo_Gallery_Update'])

         // Create a mysql query
         $sql = 'UPDATE '. GALLERY_TABLE .
         ' SET title = "' . $form['title'] . '",
	 description = "' . $form['description']. '",
	 date_updated = "' . date('Y-m-d') . '",
	 ip_updated = "' . $user_ip . '"
	 WHERE id = "' . intval($_POST['id']) . '"';

	$db->query($sql) or error ('Critical Error', mysql_error ());

      // We think that the image is uploaded or will
      // return FALSE if the upload_image function
      // will fail
      $uploaded = TRUE;

      if (isset($_POST['id']))
       $id = $_POST['id'];
      if (isset($_POST['submit_gallery']) 
       && $_POST['submit_gallery'] == $lang['Photo_Gallery_Submit']) 
       $id = mysql_insert_id();

      // Upload and resize the image
      upload_image ( 'gallery', $id, $_FILES['image_file']['tmp_name'], $conf['gallery_resampled_width'] ) or $uploaded = FALSE;


        // Output the 'Thank you' message
	echo $lang['Gallery_Updated'];

       }

      echo table_footer ( );
 
     }

    // If the item was removed from the gallery

    if (isset($_POST['remove_gallery']) 
    && $_POST['remove_gallery'] == $lang['Photo_Gallery_Remove']
    && isset($_POST['id']))
     {

      echo table_header ( $lang['Information'] );

      // Create a mysql query
      $sql = 'DELETE FROM '. GALLERY_TABLE .
             ' WHERE id = "' . safehtml($_POST['id']) . '" LIMIT 1';

      // Removing item from the gallery
      $db->query($sql) or error ('Critical Error', mysql_error ());
 
      // Removing gallery item photo
      remove_image ( 'gallery' , intval($_POST['id']));

      // Output the 'Thank you' message
      echo $lang['Gallery_Removed'];

      echo table_footer ( );

     }

    // Navigation
    echo table_header ( $lang['Navigation'] );
    // Back to the listing search page using the cached search values
    echo '- <a href="' . URL . '/admin/findlistings.php?' . $session->fetch('listingsearchvariables') . '">' . $lang['Search_Back_Listing'] . '</a><br />';

    echo table_footer ();

    //

    // Main form

    echo table_header ( $lang['Photo_Gallery'] );

    echo '<form action = "' . URL . '/admin/editgallery.php?id=' . intval($_GET['id']) . '&userid=' . intval($_GET['userid']) . '" method="POST" enctype="multipart/form-data">';

    // Print out all the image gallery items available for this
    // listing
    $sql = 'SELECT * FROM ' . GALLERY_TABLE . ' WHERE listingid = "' . safehtml($_GET['id']) . '" AND userid = "' . safehtml($_GET['userid']) . '"';

    $r_gallery = $db->query( $sql ) or error ('Critical Error', mysql_error ());

    echo '	<table width="100%" cellpadding="5" cellspacing="0" border="0">';

    $i = 0;

    while ($f_gallery = $db->fetcharray($r_gallery))
     {

      // Set background color
      $bgcolor = ''; // Background color for all odd listings
      $bgcolor2 = $conf['list_background_color_even']; // Background color for all even listings

      if ( $i%2 == 0 )
       $color = $bgcolor;
      else
       $color = $bgcolor2;

      echo ' 
	<tr>
	 <td width="10%" align="middle" bgcolor="' . $color . '"><input type="radio" name="id" value="' . $f_gallery['id'] . '"></td>
	 <td width="30%" align="middle" bgcolor="' . $color . '">' . show_gallery_image ('gallery', $f_gallery['id']) . '</td>
	 <td width="60%" align="left" valign="top" bgcolor="' . $color . '">' . $f_gallery['title'] . '<p></p><i>' . $f_gallery['description'] . '</i></td>
	</tr>
           ';

      $i++;	

     }

    echo '	</table>';

    echo table_footer();

    //

    echo table_header ( $lang['Photo_Gallery_Submit'] );

    // Define the form variables if the form was not updated
    if (!isset($form) || (isset($count_error) && $count_error == '0'))
     {
      $form = array();
      $form['title'] = '';
      $form['description'] = '';
     }

    // If image was uploaded
    if (isset($uploaded) && $uploaded)
     echo '<p align="center"><span class="warning">' . $lang['Listing_Image_Uploaded'] . '</span></p>';

    // If image was not uploaded because of the image
    // size problems etc.
    if (isset($uploaded) && !$uploaded)
     echo '<p align="center"><span class="warning">' . $lang['Listing_Image_NOT_Uploaded'] . '</span></p>';

    // Output the form
    echo '
     <table width="100%" cellpadding="5" cellspacing="0" border="0">
         ';

    echo userform ($lang['Listing_Image_File'], '<input type="file" size="40" name="image_file" maxlength="50">', '1');
    echo userform ($lang['Photo_Gallery_Title'], '<input type="text" size="45" name="title" value="' . $form['title'] . '" maxlength="255">', '1');
    echo userform ($lang['Photo_Gallery_Description'], '<textarea wrap="hard" cols="45" rows="4"  name="description" onKeyDown="textCounter(this.form.description,this.form.description_counter, ' . $conf['gallery_description_size'] . ');" onKeyUp="textCounter(this.form.description,this.form.description_counter, ' . $conf['gallery_description_size'] . ');">' . $form['description'] . '</textarea>');
    echo userform ('', '<input readonly type="text" name="description_counter" size="5" maxlength="5" value="' . $conf['gallery_description_size'] . '"> ' . $lang['Characters_Left']);
    echo userform ('', '<input type="Submit" name="submit_gallery" value="' . $lang['Photo_Gallery_Submit'] . '">');
    echo userform ('', '<input type="Submit" name="update_gallery" value="' . $lang['Photo_Gallery_Update'] . '">');
    echo userform ('', '<input type="Submit" name="remove_gallery" value="' . $lang['Photo_Gallery_Remove'] . '">');

    echo '
     </table>
         ';

    echo table_footer ();

   }

  else

   echo 'No listing ID and user ID specified.';

 }

else

 error ('Critical Error' , 'Please, login to access this script.');

// Template footer
include ( PATH . '/admin/template/footer.php' );

?>